package com.yuri.news.service.impl;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yuri.news.entity.Button;
import com.yuri.news.jpa.ButtonRepository;
import com.yuri.news.service.ButtonService;

@Service
public class ButtonServiceImpl implements ButtonService {
	@Autowired
	ButtonRepository buttonRepository;

	@Override
	public Button saveButton(Button button) {
		// 利用UUID生成唯一编码！
		String key = UUID.randomUUID().toString().replaceAll("-", "");
		button.setBtnNo(key);
		button.setInitStatus(1);
		return buttonRepository.save(button);
	}

	@Override
	public List<Button> listButton() {
		return buttonRepository.findAll();
	}

	@Override
	public Button getButtonById(Long id) {
		Button button = null;

		Optional<Button> optional = buttonRepository.findById(id);

		if (optional.isPresent()) {
			button = optional.get();
		}

		return button;
	}

	@Override
	public Boolean deleteButton(Long id) {
		Boolean flag = false;

		Optional<Button> optional = buttonRepository.findById(id);
		if (optional.isPresent()) {
			buttonRepository.deleteById(id);
			flag = true;
		}

		return flag;
	}

	@Override
	public Boolean updateButton(Button button) {
		Boolean flag = false;
		
		Optional<Button> optional = buttonRepository.findById(button.getId());
		
		if(optional.isPresent()) {
			if(button.getMenuNo() == null) {
				button.setMenuNo(optional.get().getMenuNo());
			}
			if(button.getMenuNo() != null && button.getMenuNo().getId() == -1) {
				button.setMenuNo(null);
			}
			buttonRepository.save(button);
			flag = true;
		}
		return flag;
	}

}
